/**
 * 简化的合并面板组件
 * 只提供基础的合并操作，去掉复杂的智能建议
 */

import React, { useState } from 'react';
import type { Room } from '../../../types/room';
import type { SimpleMergedBlock } from '../hooks/useSimpleMerge';
import styles from '../styles/SimpleMergePanel.module.css';

export interface SimpleMergePanelProps {
  visible: boolean;
  mergedBlocks: SimpleMergedBlock[];
  selectedCells: { roomId: string; date: string }[];
  rooms: Room[];
  stats: {
    totalBlocks: number;
    totalDays: number;
    savedCells: number;
  };
  onClose: () => void;
  onMergeSelected: (guestName?: string, note?: string) => void;
  onSplitBlock: (blockId: string) => void;
  onUpdateBlock: (
    blockId: string,
    updates: { guestName?: string; note?: string }
  ) => void;
  onClearAll: () => void;
}

const SimpleMergePanel: React.FC<SimpleMergePanelProps> = ({
  visible,
  mergedBlocks,
  selectedCells,
  rooms,
  stats,
  onClose,
  onMergeSelected,
  onSplitBlock,
  onUpdateBlock,
  onClearAll,
}) => {
  const [guestName, setGuestName] = useState('');
  const [note, setNote] = useState('');
  const [editingBlock, setEditingBlock] = useState<string | null>(null);
  const [editGuestName, setEditGuestName] = useState('');
  const [editNote, setEditNote] = useState('');

  if (!visible) return null;

  const getRoomName = (roomId: string) => {
    const room = rooms.find(r => r.id === roomId);
    return room ? room.roomNumber : roomId;
  };

  const handleMerge = () => {
    onMergeSelected(guestName.trim() || undefined, note.trim() || undefined);
    setGuestName('');
    setNote('');
  };

  const handleEdit = (block: SimpleMergedBlock) => {
    setEditingBlock(block.id);
    setEditGuestName(block.guestName || '');
    setEditNote(block.note || '');
  };

  const handleSaveEdit = () => {
    if (editingBlock) {
      onUpdateBlock(editingBlock, {
        guestName: editGuestName.trim() || undefined,
        note: editNote.trim() || undefined,
      });
      setEditingBlock(null);
      setEditGuestName('');
      setEditNote('');
    }
  };

  const handleCancelEdit = () => {
    setEditingBlock(null);
    setEditGuestName('');
    setEditNote('');
  };

  return (
    <div className={styles.panel}>
      <div className={styles.header}>
        <h3 className={styles.title}>🔗 合并管理</h3>
        <button className={styles.closeButton} onClick={onClose}>
          ✕
        </button>
      </div>

      {/* 统计信息 */}
      <div className={styles.stats}>
        <div className={styles.statItem}>
          <span className={styles.statNumber}>{stats.totalBlocks}</span>
          <span className={styles.statLabel}>合并块</span>
        </div>
        <div className={styles.statItem}>
          <span className={styles.statNumber}>{stats.totalDays}</span>
          <span className={styles.statLabel}>总天数</span>
        </div>
        <div className={styles.statItem}>
          <span className={styles.statNumber}>{stats.savedCells}</span>
          <span className={styles.statLabel}>节省单元格</span>
        </div>
      </div>

      {/* 快速合并 */}
      {selectedCells.length > 1 && (
        <div className={styles.mergeSection}>
          <h4>合并选中单元格 ({selectedCells.length}个)</h4>
          <div className={styles.inputGroup}>
            <input
              type='text'
              placeholder='客人姓名（可选）'
              value={guestName}
              onChange={e => setGuestName(e.target.value)}
              className={styles.input}
            />
            <input
              type='text'
              placeholder='备注信息（可选）'
              value={note}
              onChange={e => setNote(e.target.value)}
              className={styles.input}
            />
          </div>
          <button className={styles.mergeButton} onClick={handleMerge}>
            🔗 合并
          </button>
        </div>
      )}

      {/* 已合并块列表 */}
      <div className={styles.blocksList}>
        <div className={styles.listHeader}>
          <h4>已合并预订</h4>
          {mergedBlocks.length > 0 && (
            <button className={styles.clearAllButton} onClick={onClearAll}>
              清空全部
            </button>
          )}
        </div>

        {mergedBlocks.length === 0 ? (
          <div className={styles.emptyState}>
            <p>还没有合并的预订</p>
            <p>选择连续的单元格并点击合并按钮</p>
          </div>
        ) : (
          mergedBlocks.map(block => (
            <div key={block.id} className={styles.blockCard}>
              {editingBlock === block.id ? (
                // 编辑模式
                <div className={styles.editMode}>
                  <div className={styles.blockInfo}>
                    <strong>🏨 {getRoomName(block.roomId)}</strong>
                    <span>
                      {block.dates.length}天 ({block.startDate} ~{' '}
                      {block.endDate})
                    </span>
                  </div>
                  <div className={styles.editInputs}>
                    <input
                      type='text'
                      placeholder='客人姓名'
                      value={editGuestName}
                      onChange={e => setEditGuestName(e.target.value)}
                      className={styles.editInput}
                    />
                    <input
                      type='text'
                      placeholder='备注信息'
                      value={editNote}
                      onChange={e => setEditNote(e.target.value)}
                      className={styles.editInput}
                    />
                  </div>
                  <div className={styles.editActions}>
                    <button
                      className={styles.saveButton}
                      onClick={handleSaveEdit}
                    >
                      ✅ 保存
                    </button>
                    <button
                      className={styles.cancelButton}
                      onClick={handleCancelEdit}
                    >
                      ❌ 取消
                    </button>
                  </div>
                </div>
              ) : (
                // 显示模式
                <div className={styles.displayMode}>
                  <div className={styles.blockHeader}>
                    <div className={styles.blockTitle}>
                      <strong>🏨 {getRoomName(block.roomId)}</strong>
                      <span className={styles.duration}>
                        {block.dates.length}天
                      </span>
                    </div>
                    <div className={styles.blockActions}>
                      <button
                        className={styles.editButton}
                        onClick={() => handleEdit(block)}
                      >
                        ✏️
                      </button>
                      <button
                        className={styles.splitButton}
                        onClick={() => onSplitBlock(block.id)}
                      >
                        ✂️
                      </button>
                    </div>
                  </div>

                  <div className={styles.blockDetails}>
                    <p>
                      📅 {block.startDate} → {block.endDate}
                    </p>
                    {block.guestName && <p>👤 {block.guestName}</p>}
                    {block.note && <p>📝 {block.note}</p>}
                  </div>
                </div>
              )}
            </div>
          ))
        )}
      </div>
    </div>
  );
};

export default SimpleMergePanel;
